package websocket2

import (
	"bytes"
	"encoding/binary"
)

const (
	headLen = 4
	actLen  = 1
)

var defaultHead = []byte{0x04, 0x02, 0x01, 0x03} //数据包头

type PacketData struct {
	Act      int
	Data     []byte
	SourceId string
}

func NewPacketData(act int, data []byte) *PacketData {
	return &PacketData{Act: act, Data: data}
}

func byte2int(src []byte) (ret int) {
	var tmp int32
	b_buf := bytes.NewBuffer(src)
	binary.Read(b_buf, binary.BigEndian, &tmp)
	ret = int(tmp)
	return
}
func int2byte(src int) []byte {
	var tmp int32
	tmp = int32(src)
	b_buf := bytes.NewBuffer([]byte{})
	binary.Write(b_buf, binary.BigEndian, tmp)
	return b_buf.Bytes()
}

func EnPacket(act int, data []byte) (ret []byte) {
	ret = append(defaultHead)
	ret = append(ret, int2byte(4+len(data))...)
	ret = append(ret, int2byte(act)...)
	ret = append(ret, data...)
	return
}

func Parse(bs []byte) (act int, ret []byte) {
	act = byte2int(bs[:4])
	ret = bs[4:]
	return
}
